/*
 * @Description:
 * @FilePath: /STM32/USER/bsp/tim.c
 * @Author: Wei Zhou
 * @Github: https://github.com/zromyk
 * @Date: 2021-04-28 15:25:19
 * @LastEditors: Wei Zhou
 * @LastEditTime: 2021-04-28 15:25:19
 * @Copyright: Copyright  2017 muyiro. All rights reserved.
 */

#include "tim.h"
#include "gpio.h"
#include "nvic.h"
#include "rcc.h"

TIM_Dev tim3 =
{
    .TIMx           = TIM3,
    .RCC_Periph_TIM = RCC_APB1Periph_TIM3,
    .TIMx_IRQn      = TIM3_IRQn
};

TIM_Dev tim7 =
{
    .TIMx           = TIM7,
    .RCC_Periph_TIM = RCC_APB1Periph_TIM7,
    .TIMx_IRQn      = TIM7_IRQn
};

void tim_us_init(TIM_Dev *tim, uint16_t us, uint8_t priority, uint8_t subPriority)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;

    rcc_periph_clock_enable(tim->TIMx, tim->RCC_Periph_TIM);

    TIM_TimeBaseInitStruct.TIM_Period = us - 1;
    TIM_TimeBaseInitStruct.TIM_Prescaler = rcc_periph_clock_rate(tim->TIMx) - 1;
    TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInit(tim->TIMx, &TIM_TimeBaseInitStruct);

    nvic_configuration(tim->TIMx_IRQn, priority, subPriority);
    TIM_ITConfig(tim->TIMx, TIM_IT_Update, ENABLE);
    TIM_Cmd(tim->TIMx, ENABLE);
}

void tim_ms_init(TIM_Dev *tim, uint16_t ms, uint8_t priority, uint8_t subPriority)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;

    rcc_periph_clock_enable(tim->TIMx, tim->RCC_Periph_TIM);

    TIM_TimeBaseInitStruct.TIM_Period = ms * 10 - 1;
    TIM_TimeBaseInitStruct.TIM_Prescaler = rcc_periph_clock_rate(tim->TIMx) * 100 - 1;
    TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInit(tim->TIMx, &TIM_TimeBaseInitStruct);

    nvic_configuration(tim->TIMx_IRQn, priority, subPriority);
    TIM_ITConfig(tim->TIMx, TIM_IT_Update, ENABLE);
    TIM_Cmd(tim->TIMx, ENABLE);
}
